// service worker version number
const SW_VERSION = 3;
// the root name for our cache
const CACHE_ROOT = 'slimesim'
// generates a custom cache name per service worker version
const CACHE_NAME = `${CACHE_ROOT}-v${SW_VERSION}`;

var urlList = [
  '/app.webmanifest',
  '/slimsimgl.html',
  '/libs/jsoneditor.min.css',
  '/libs/jsoneditor.min.js',  
];

self.addEventListener('install', event => {
  event.waitUntil(
    caches.open('CACHE_NAME')
      .then(cache => {
        return cache.addAll(urlList);
      })
      .catch(error => {
        console.error(error);
      })
  );
});

self.addEventListener('activate', event => {
  event.waitUntil(
    caches.keys().then(cacheList => {
      return Promise.all(
        cacheList.map(theCache => {
          if ((CACHE_NAME !== theCache) && (theCache.startsWith(CACHE_ROOT))) {
            //delete cached contents of previous versions
            return caches.delete(theCache);
          }
        })
      );
    })
  );
});

self.addEventListener('fetch', event => {  
  console.log("fetch ", event.request);
  event.respondWith( 
    caches.match(event.request)
      .then(response => { 
        if (response) { 
          return response;
        }  
        return fetch(event.request)
          .catch(() => { 
            if (vent.request.headers.get('accept').includes('text/html')) {
              return caches.match("/slimsimgl.html");
            }
          })
      })
  );
});